<?php

namespace app\home\controller;

use app\common\controller\BaseController;
use app\common\model\distribute\HandleRedMotherCommission;
use app\common\model\distribute\HandleVideoAuthCommission;
use app\common\model\hfztcy\LibAdminBalanceRecords;
use app\common\model\hfztcy\LibBalanceRecords;
use app\common\model\hfztcy\LibConfig;
use app\common\model\hfztcy\LibEvaluation;
use app\common\model\hfztcy\LibMember;
use app\common\model\hfztcy\LibOrder;
use app\common\model\hfztcy\LibOrderVipAuth;
use app\common\model\LibAdmin;
use app\common\model\LibUser;
use common\Common;
use think\Db;

/**
 *
 * @name Cron.php
 * @package hfztcy
 * @category controller
 * @link http://www.changekeji.com
 * @author rxy
 * @version 2.0
 * @copyright CHANGE INC
 * @since 2022-06-22
 */
class Cron extends BaseController
{
    /**
     * Info: 检测VIP用户是否过期
     * Date: 2022/11/21 9:23
     */
    public function checkMemberStatusByCrontab()
    {
        $sql = "SELECT `id`,`user_id`,`vip_open_time`,`state` FROM `hfztcy_user` where vip_open_time > 0";
        $result = Db::query($sql);
        //$memberModel = new LibMember();
        foreach ($result as $item) {
            if ($item['vip_open_time'] < time()) {
                $user_id = $item['user_id'];
                //$memberModel->updateMemberState($item['user_id']);
                $sql = <<< SQL
SELECT identity FROM `base_user` WHERE `id` = {$user_id}
SQL;
                $userRes = Db::query($sql);
                $identity = [];
                if ($userRes) {
                    $identity = explode(',',$userRes[0]['identity']);
                }
                $identity = array_map('intval',$identity);
                //移除vip会员身份
                $identity = array_map(function ($val) use ($identity) {
                    if ($val == 2) {
                        unset($identity[$val]);
                    } else {
                        return $val;
                    }
                },$identity);
                //重置为普通用户
                $identity = array_filter($identity);
                $identity = array_unique($identity);
                if (empty($identity)) array_push($identity,1);
                if ($identity) {
                    $identityStr = implode(',', $identity);
                    $sql = <<< SQL
UPDATE base_user 
SET identity='{$identityStr}' 
WHERE `id` = '{$user_id}'
SQL;
                    Db::execute($sql);

                    $sql = <<< SQL
UPDATE hfztcy_user 
SET is_vip=0,vip_open_time=0,state='{$identityStr}' 
WHERE `user_id` = '{$user_id}'
SQL;
                    Db::execute($sql);
                } else {
                    $sql = <<< SQL
UPDATE hfztcy_user 
SET vip_open_time=0
WHERE `user_id` = '{$user_id}'
SQL;
                    Db::execute($sql);
                }
            }
        }
    }

    /**
     * Info: 检查会员团队注册会员数量
     * Date: 2022/11/21 9:37
     */
    public function checkMemberTeamRegisterUserByCrontab ()
    {
        set_time_limit(0);
        $date = strtotime(date('Y-m-d H:00:00'));
        //dump(date('Y-m-d H',$date));
        $nextDate = (int)$date  + 3600;
        //dump(date('Y-m-d H',$nextDate));
        $sql = <<< SQL
SELECT
    `id`,
    `identity`
FROM
    `base_user`
WHERE 
    (exec_time_by_register =  {$date}  OR exec_time_by_register = 0) AND is_give_meet = 0 AND FIND_IN_SET(1,identity)
LIMIT 50
SQL;
        //dump($sql);
        $result = Db::query($sql);
        $configModel = new LibConfig();
        $findConfigRes = $configModel->findConfig(['item_key' => 'direct_register_member_count']);
        $new_user_count = $findConfigRes['data']['item_value'];
        foreach ($result as $item)
        {
            // 更新执行时间
            $sql = "UPDATE `base_user` SET `exec_time_by_register`='{$nextDate}' WHERE  `id`={$item['id']};";
            Db::execute($sql);
            //dump($sql);
            // 统计直推会员数量
            $sql = <<< SQL
SELECT  count(*) num
FROM `base_user` AS a 
    INNER JOIN `hfztcy_user` AS b ON a.id = b.user_id 
WHERE a.parent_id = {$item['id']}
SQL;
            $res = Db::query($sql);
            //dump($res);
            if ($res && $res[0]['num'] > $new_user_count) {
                $time = Common::getTime();
                $sql = "INSERT INTO `hfztcy_member_achieve` (`user_id`,`add_time`,`describe`) VALUES ('{$item['id']}','{$time}','赠送一次线下见面会');";
                Db::execute($sql);
                $insertId = Db::getLastInsID();
                // 更新字段
                $sql = "UPDATE `base_user` SET `is_give_meet`='{$insertId}' WHERE  `id`={$item['id']};";
                Db::execute($sql);
            }
        }
    }

    /**
     * Info: 检查红娘团队注册会员数量
     * Date: 2023/2/13 13:45
     */
    public function checkMemberRedMotherRegisterUserCountByCrontab ()
    {
        set_time_limit(0);
        $date = strtotime(date('Y-m-d H:00:00'));
        //dump(date('Y-m-d H',$date));
        $nextDate = (int)$date  + 3600;
        //dump(date('Y-m-d H',$nextDate));
        $sql = <<< SQL
SELECT
    `user_id`,
    `state`
FROM
    `hfztcy_user`
WHERE 
    (exec_time_by_register =  {$date}  OR exec_time_by_register = 0) AND FIND_IN_SET(3,state)
LIMIT 50
SQL;
        //dump($sql);
        $result = Db::query($sql);
        foreach ($result as $item)
        {
            // 更新执行时间
            $sql = "UPDATE `hfztcy_user` SET `exec_time_by_register`='{$nextDate}' WHERE  `user_id`={$item['user_id']};";
            Db::execute($sql);
            //dump($sql);
            // 统计直推会员数量
            $sql = <<< SQL
SELECT  count(*) num
FROM `base_user` AS a 
    INNER JOIN `hfztcy_user` AS b ON a.id = b.user_id 
WHERE a.parent_id = {$item['user_id']}
SQL;
            $res = Db::query($sql);
            //dump($res);
            if ($res && $res[0]['num']) {
                // 更新字段
                $sql = "UPDATE `hfztcy_user` SET `register_user_count`='{$res[0]['num']}' WHERE  `user_id`={$item['user_id']};";
                Db::execute($sql);
            }
        }
    }

    /**
     * Info: 检查红娘团队付费红娘数量
     * Date: 2022/11/21 9:37
     */
    public function checkMemberRedMotherTeamByCrontab ()
    {
        set_time_limit(0);
        $date = strtotime(date('Y-m-d H:00:00'));
        //dump(date('Y-m-d H',$date));
        $nextDate = (int)$date  + 3600;
        //dump(date('Y-m-d H',$nextDate));
        $sql = <<< SQL
SELECT
    `id`,
    `identity`
FROM
    `base_user`
WHERE 
    (exec_time_by_redmother =  {$date}  OR exec_time_by_redmother = 0) AND is_give_red_mother = 0 AND FIND_IN_SET(1,identity)
LIMIT 50
SQL;
        //dump($sql);
        $result = Db::query($sql);
        $configModel = new LibConfig();
        $findConfigRes = $configModel->findConfig(['item_key' => 'direct_red_mother_count']);
        $pay_red_mother_count = $findConfigRes['data']['item_value'];
        foreach ($result as $item)
        {
            // 更新执行时间
            $sql = "UPDATE `base_user` SET `exec_time_by_redmother`='{$nextDate}' WHERE  `id`={$item['id']};";
            //dump($sql);
            Db::execute($sql);

            $sql = <<< SQL
SELECT count(*) num FROM `hfztcy_member_distribute` as a
left JOIN `base_user` as b on a.user_id = b.id
WHERE a.`pid` = {$item['id']} and FIND_IN_SET(3,identity)
SQL;
            $res = Db::query($sql);
            //dump($res);
            if ($res && $res[0]['num'] > $pay_red_mother_count) {

                // 插入记录
                $time = Common::getTime();
                $sql = "INSERT INTO `hfztcy_member_achieve` (`user_id`,`add_time`,`describe`) VALUES ('{$item['id']}','{$time}','赠送红娘身份');";
                Db::execute($sql);
                $insertId = Db::getLastInsID();
                // 更新字段
                $sql = "UPDATE `base_user` SET `is_give_red_mother`='{$insertId}' WHERE  `id`={$item['id']};";
                Db::execute($sql);

                // 增加红娘身份
                $identity = array_map('intval',explode(',',$item['identity']));
                array_push($identity,3);
                //排除游客，普通会员，增加红娘身份
                $identity = array_map(function ($val) use ($identity) {
                    if ($val <= 1) {
                        unset($identity[$val]);
                    } else {
                        return $val;
                    }
                },$identity);
                $identity = array_filter($identity);
                $identity = array_unique($identity);
                if ($identity) {
                    $identityStr = implode(',',$identity);
                    $sql = <<< SQL
UPDATE base_user 
SET identity='{$identityStr}' 
WHERE `id` = '{$item['id']}'
SQL;
                    Db::execute($sql);

                    $sql = <<< SQL
UPDATE hfztcy_user 
SET state='{$identityStr}',is_platform_give=1 
WHERE `user_id` = '{$item['id']}'
SQL;
                    Db::execute($sql);
                }
            }
        }
    }

    /**
     * Info: 红娘对平台的评论
     * Date: 2022/11/22 14:45
     */
    public function checkRedMotherEvaluateByCrontab ()
    {
        $date = date('Y-m-d');
        $timestamp = strtotime($date);
        $l = date('l',$timestamp);
        $l = strtolower($l);
        if ($l == 'sunday') {
            $time = time();
            $zero = $date.' 23:59:00';
            $zero = strtotime($zero);
            if ($zero <= $time) {
                $model = new LibEvaluation();
                $weeks = $this->getWeekRange($time);
                $sql = "SELECT * FROM `hfztcy_user` WHERE FIND_IN_SET(3,state) AND audit_state = 1";
                $query = Db::query($sql);
                if ($query) {
                    foreach ($query as $item) {
                        $sql = <<< SQL
SELECT count(*) num FROM `hfztcy_evaluation` WHERE `user_id` = {$item['user_id']} AND (`add_time` >= '{$weeks['sdate']}' AND `add_time` <= '{$weeks['edate']}')
SQL;
                        $res = Db::query($sql);
                        if ($res && $res[0]['num'] == 0) {
                            $data = [];
                            $data['user_id'] = $item['user_id'];
                            $data['star_num'] = 5;
                            $data['content'] = '系统默认好评';
                            $data['add_time'] = Common::getTime();
                            $data['type'] = 0;
                            $model->addEvaluation($data);
                        }
                    }
                }
            }
        }
    }

    /**
     * Info: 门店对平台的评论
     * Date: 2022/11/22 14:45
     */
    public function checkStoreEvaluateByCrontab ()
    {
        $date = date('Y-m-d');
        $timestamp = strtotime($date);
        $l = date('l',$timestamp);
        $l = strtolower($l);
        if ($l == 'sunday') {
            $time = time();
            $zero = $date.' 23:59:00';
            $zero = strtotime($zero);
            if ($zero <= $time) {
                $model = new LibEvaluation();
                $weeks = $this->getWeekRange($time);
                $sql = "SELECT a.*,b.uid 
FROM `hfztcy_user` AS a LEFT JOIN `hfztcy_store` AS b 
    ON a.user_id = b.uid 
WHERE FIND_IN_SET(4,a.state) AND a.audit_state = 1 AND b.state = 0";
                $query = Db::query($sql);
                if ($query) {
                    foreach ($query as $item) {
                        $sql = <<< SQL
SELECT count(*) num FROM `hfztcy_evaluation` WHERE `user_id` = {$item['user_id']} AND (`add_time` >= '{$weeks['sdate']}' AND `add_time` <= '{$weeks['edate']}')
SQL;
                        $res = Db::query($sql);
                        if ($res && $res[0]['num'] == 0) {
                            $data = [];
                            $data['user_id'] = $item['user_id'];
                            $data['star_num'] = 5;
                            $data['content'] = '系统默认好评';
                            $data['add_time'] = Common::getTime();
                            $data['type'] = 1;
                            $model->addEvaluation($data);
                        }
                    }
                }
            }
        }
    }

    /**
     * Info: 当红娘注册的时间超过7天，发放冻结中的收益
     * Date: 2023/1/10 9:27
     */
    public function grantRedMotherFreezeCommission ()
    {
        $sql = <<< SQL
SELECT
    a.*,
    b.direct_user_id,
    b.indirect_user_id,
    b.shi_admin_id,
    b.xian_admin_id,
    b.kf_admin_id,
    b.px_admin_id,
    b.zt_commission_money,
    b.jt_commission_money,
    b.shi_commission_money,
    b.xian_commission_money,
    b.kf_commission_money,
    b.px_commission_money
FROM
    `hfztcy_order` AS `a`
INNER JOIN `hfztcy_order_red_mother` AS `b`
ON
    `a`.`id` = `b`.`order_id`
WHERE
    a.type = 3 AND a.transaction_id IS NOT NULL AND a.exec_state = 0 AND (TO_DAYS(NOW()) - TO_DAYS(date(pay_time))) > 7
ORDER BY
    `a`.`user_id` ASC;
SQL;
        $query = Db::query($sql);
        $memberModel = new LibMember();
        $userModel = new LibUser();
        $balanceRecordsModel = new LibBalanceRecords();
        $adminBalanceRecordsModel = new LibAdminBalanceRecords();
        $adminModel = new LibAdmin();
        $orderModel = new LibOrder();
        foreach ($query as $item)
        {
            $direct_user_id = $item['direct_user_id'];
            $indirect_user_id = $item['indirect_user_id'];
            $shi_admin_id = $item['shi_admin_id'];
            $xian_admin_id = $item['xian_admin_id'];
            $kf_admin_id = $item['kf_admin_id'];
            $px_admin_id = $item['px_admin_id'];
            $zt_commission_money = $item['zt_commission_money'];
            $jt_commission_money = $item['jt_commission_money'];
            $shi_commission_money = $item['shi_commission_money'];
            $xian_commission_money = $item['xian_commission_money'];
            $kf_commission_money = $item['kf_commission_money'];
            $px_commission_money = $item['px_commission_money'];
            // 直推红娘
            if ($item['direct_user_id'])
                HandleRedMotherCommission::updateDirectUserCommission(
                    $memberModel,
                    $userModel,
                    $balanceRecordsModel,
                    $direct_user_id,
                    $item['id'],
                    $zt_commission_money);
            // 间推红娘
            if ($item['indirect_user_id'])
                HandleRedMotherCommission::updateIndirectUserCommission(
                    $memberModel,
                    $userModel,
                    $balanceRecordsModel,
                    $indirect_user_id,
                    $item['id'],
                    $jt_commission_money);
            // 市代用户
            if ($item['shi_admin_id'])
                HandleRedMotherCommission::updateShiAdminCommission(
                    $adminModel,
                    $adminBalanceRecordsModel,
                    $shi_admin_id,
                    $item['id'],
                    $shi_commission_money);
            // 区县代用户
            if ($item['xian_admin_id'])
                HandleRedMotherCommission::updateXianAdminCommission(
                    $adminModel,
                    $adminBalanceRecordsModel,
                    $xian_admin_id,
                    $item['id'],
                    $xian_commission_money);
            // 客服部
            if ($item['kf_admin_id'])
                HandleRedMotherCommission::updateKfAdminCommission(
                    $adminModel,
                    $adminBalanceRecordsModel,
                    $kf_admin_id,
                    $item['id'],
                    $kf_commission_money);
            // 培训部
            if ($item['px_admin_id'])
                HandleRedMotherCommission::updatePxAdminCommission(
                    $adminModel,
                    $adminBalanceRecordsModel,
                    $px_admin_id,
                    $item['id'],
                    $px_commission_money);

            $orderModel->updateOrder(['id' => $item['id']] , ['exec_state' => 1]);
        }
    }

    /**
     * Info: 当视频认证的认证时间超过7天，发放冻结中的收益
     * Date: 2023/1/10 18:47
     */
    public function grantVideoAuthFreezeCommission ()
    {
        $sql = <<< SQL
SELECT
    a.*,
    b.direct_user_id,
    b.indirect_user_id,
    b.shi_admin_id,
    b.xian_admin_id,
    b.kf_admin_id,
    b.px_admin_id,
    b.store_user_id,
    b.store_parent_user_id,
    b.zt_commission_money,
    b.jt_commission_money,
    b.shi_commission_money,
    b.xian_commission_money,
    b.kf_commission_money,
    b.px_commission_money,
    b.store_parent_user_commission_money,
    b.md_commission_money,
    b.md_give_red_mother_commission_money
FROM
    `hfztcy_order` AS `a`
INNER JOIN `hfztcy_order_vip_auth` AS `b`
ON
    `a`.`id` = `b`.`order_id`
WHERE
    a.type = 2 AND a.transaction_id IS NOT NULL AND a.exec_state = 0 AND (TO_DAYS(NOW()) - TO_DAYS(date(pay_time))) > 7
ORDER BY
    `a`.`user_id` ASC;
SQL;
        $query = Db::query($sql);
        $memberModel = new LibMember();
        $userModel = new LibUser();
        $balanceRecordsModel = new LibBalanceRecords();
        $adminBalanceRecordsModel = new LibAdminBalanceRecords();
        $adminModel = new LibAdmin();
        $orderModel = new LibOrder();
        foreach ($query as $item) {
            $direct_user_id = $item['direct_user_id'];
            $indirect_user_id = $item['indirect_user_id'];
            $shi_admin_id = $item['shi_admin_id'];
            $xian_admin_id = $item['xian_admin_id'];
            $kf_admin_id = $item['kf_admin_id'];
            $px_admin_id = $item['px_admin_id'];
            $store_user_id = $item['store_user_id'];
            $store_parent_user_id = $item['store_parent_user_id'];
            $zt_commission_money = $item['zt_commission_money'];
            $jt_commission_money = $item['jt_commission_money'];
            $shi_commission_money = $item['shi_commission_money'];
            $xian_commission_money = $item['xian_commission_money'];
            $kf_commission_money = $item['kf_commission_money'];
            $px_commission_money = $item['px_commission_money'];
            $md_commission_money = $item['md_commission_money'];
            $md_give_red_mother_commission_money = $item['md_give_red_mother_commission_money'];
            $store_parent_user_commission_money = $item['store_parent_user_commission_money'];
            // 直推红娘
            if ($item['direct_user_id'])
                HandleVideoAuthCommission::updateDirectUserCommission(
                    $memberModel,
                    $userModel,
                    $balanceRecordsModel,
                    $direct_user_id,
                    $item['id'],
                    $zt_commission_money);
            // 间推红娘
            if ($item['indirect_user_id'])
                HandleVideoAuthCommission::updateIndirectUserCommission(
                    $memberModel,
                    $userModel,
                    $balanceRecordsModel,
                    $indirect_user_id,
                    $item['id'],
                    $jt_commission_money);
            // 市代用户
            if ($item['shi_admin_id'])
                HandleVideoAuthCommission::updateShiAdminCommission(
                    $adminModel,
                    $adminBalanceRecordsModel,
                    $shi_admin_id,
                    $item['id'],
                    $shi_commission_money);
            // 区县代用户
            if ($item['xian_admin_id'])
                HandleVideoAuthCommission::updateXianAdminCommission(
                    $adminModel,
                    $adminBalanceRecordsModel,
                    $xian_admin_id,
                    $item['id'],
                    $xian_commission_money);
            // 客服部
            if ($item['kf_admin_id'])
                HandleVideoAuthCommission::updateKfAdminCommission(
                    $adminModel,
                    $adminBalanceRecordsModel,
                    $kf_admin_id,
                    $item['id'],
                    $kf_commission_money);
            // 培训部
            if ($item['px_admin_id'])
                HandleVideoAuthCommission::updatePxAdminCommission(
                    $adminModel,
                    $adminBalanceRecordsModel,
                    $px_admin_id,
                    $item['id'],
                    $px_commission_money);
            // 门店用户
            if ($item['store_user_id']) {
                $store_commission_money = $md_commission_money + $md_give_red_mother_commission_money;
                HandleVideoAuthCommission::updateStoreUserCommission(
                    $adminModel,
                    $userModel,
                    $balanceRecordsModel,
                    $store_user_id,
                    $item['id'],
                    $store_commission_money);
            }
            // 门店上级用户
            if ($item['store_parent_user_id'])
                HandleVideoAuthCommission::updateStoreParentUserCommission(
                    $adminModel,
                    $userModel,
                    $balanceRecordsModel,
                    $store_parent_user_id,
                    $item['id'],
                    $store_parent_user_commission_money);

            $orderModel->updateOrder(['id' => $item['id']] , ['exec_state' => 1]);
        }
    }

    private function getWeekRange($date)
    {
        $ret = array();
        $timestamp = strtotime($date);
        $w = strftime('%u', $timestamp);
        $ret['sdate'] = date('Y-m-d 00:00:00', $timestamp - ($w - 1) * 86400);
        $ret['edate'] = date('Y-m-d 23:59:59', $timestamp + (7 - $w) * 86400);
        return $ret;
    }

    public function getUserTeam ()
    {
        $userModel = new LibUser();
        $findUserListRes = $userModel->findAllUser(['examine' => ['<>',date('YmdH')]],'200');
        foreach ($findUserListRes['data'] as $item)
        {
            $userModel->updateUser(['id' => $item['id']] , ['examine' => date('YmdH')]);
            $user_id = $item['id'];
            $sql = "SELECT * FROM `hfztcy_member_distribute` WHERE `one_user_id` = {$user_id} ORDER BY `id` DESC;";
            $findParentUserRes = Db::query($sql);
            if ($findParentUserRes)
            {
                $sql = "SELECT * FROM `hfztcy_member_distribute` WHERE `user_id` = {$user_id} ORDER BY `id` DESC;";
                $findUserRes = Db::query($sql);
                foreach ($findParentUserRes as $user)
                {
                    if ($user['two_user_id'] != $findUserRes[0]['one_user_id'])
                    {
                        $str = "id：{$user['id']}|one_user_id：{$user['one_user_id']}|two_user_id：{$user['two_user_id']}|user_id：{$user['user_id']}";
                        dump($str);
                    }
                }
            }
        }
    }
}